package com.gljx.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gljx.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gljx.web.Entity.CoaceGroup;
import com.gljx.web.Entity.CoaceGroupEntry;
import com.gljx.web.Entity.Department;
import com.gljx.web.Entity.PageBean;
import com.gljx.web.Entity.Person;
import com.gljx.web.Entity.Team;
import com.gljx.web.Entity.User;
import com.gljx.web.service.CoaceGroupEntryService;
import com.gljx.web.service.CoaceGroupService;
import com.gljx.web.service.CustomLogService;
import com.gljx.web.service.DepartmentService;
import com.gljx.web.service.PersonService;
import com.gljx.web.service.TeamService;

@Controller
@RequestMapping("/")
public class CoaceGroupController {

	//自动注入
	@Autowired
	private CoaceGroupService coaceGroupService;
	 
	//自动注入
	@Autowired
	private CustomLogService  customLogService;
	
	//自动注入
	@Autowired
	private PersonService personService;
		
	//自动注入
	@Autowired
	private DepartmentService departmentService;
	
	//自动注入
	@Autowired
	private TeamService teamService;
	
	//自动注入
	@Autowired
	private CoaceGroupEntryService coaceGroupEntryService;
	/**
	 * 查询教练组
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryCoaceGroup/look.action")
	public String queryCoaceGroup(HttpServletRequest request, String flag) {
		PageBean<CoaceGroup>pb = new PageBean<>();
		//获取操作人信息
	    User user = (User)request.getSession().getAttribute("user");
		try {
			//获取分页
			pb = getPageBean(request,user.getFcompanyid());
			//获取当前分页的值
			List<CoaceGroup> coaceGroups = pb.getBeanList();
			//把获取到的数据传回页面
			request.setAttribute("coaceGroups", coaceGroups);
			request.setAttribute("pb", pb);
			request.setAttribute("flag", flag);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/backHome/personData/coaceGroups/coaceGroupsList";
	}
	
	/**
	 * 根据名称查询
	 * @param request 
	 * @param fnameL2 名称
	 * @return
	 */
	@RequestMapping("/queryCoaceGroupByFnameL2")
	public String queryCoaceGroupByFnameL2(HttpServletRequest request,String fnameL2){
		PageBean<CoaceGroup> pb = new PageBean<>();
		//获取操作人信息
	    User user = (User)request.getSession().getAttribute("user");
		if("".equals(fnameL2)){
			queryCoaceGroup(request, null);//为空就调用查询的方法
		}else{
			//去除空格
			fnameL2 = fnameL2.trim();
			//查询数据
			List<CoaceGroup> coaceGroups = coaceGroupService.queryCoaceGroupByFnameL2(user.getFcompanyid(), fnameL2);
			//总记录数
			pb.setTr(coaceGroups.size());
			//每页记录数
			pb.setPs(50);
			//把数据传到页面
			request.setAttribute("coaceGroups", coaceGroups);
			request.setAttribute("pb", pb);
			request.setAttribute("fnameL2", fnameL2);
		}
		return "/backHome/personData/coaceGroups/coaceGroupsList";
	}
	
	/**
	 * 跳转到添加页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/insertCoaceGroup")
	public String insertCoaceGroup(HttpServletRequest request,String type){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//获取最大最大编码
        /*String fnumber =  customLogService.selectFunmber("CT_DS_COACEGROUP",user.getFcompanyid());*/
		//获取下一个编码
        String number = GetFnumber.fnumbers("DC");
		//查询组织
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//拼接SQL语句
    	StringBuffer psql = new StringBuffer();
    	psql.append("select T.FID, T.FNUMBER,to_char(t.CFBIRTHDAY,'YYYY-MM-DD ') cfbirthdays,to_char(t.cfstartdate,'YYYY-MM-DD ') cfstartdate,");
		psql.append("to_char(t.cfenddate,'YYYY-MM-DD ') cfenddate,to_char(t.cfbegindate,'YYYY-MM-DD ') cfbegindate,to_char(t.CFHTDQSJ,'YYYY-MM-DD ') cfhtdqsj,");
		psql.append("T.CFIDCARDNO, T.CFCELL, T.CFADDRESS,T.CFPERSONTYPE, T.CFSEX,T.CFXCTZ, T.CFGWYD, T.CFQJJL, T.CFWJJLJL,p.fname_l2 as positiongradeName,t.cfaccountsno, ");
		psql.append("T.CFSHJLJL,T.FNAME_L2,T.CFZSTC,T.CFPXTC,A.FNAME_L2 AS CFPERSONDEPNAME,C.fnumber AS CFCARNAME from ct_ds_person t left join ");
		psql.append("CT_DS_ADMIN A ON A.FID=T.CFPERSONDEPID left join CT_DS_CAR C ON C.FID=T.CFCARID left join CT_DS_POSITIONGRADE p on t.cfjobgradeid=p.fid ");
		psql.append(" where t.cfficompanyid = '" + user.getFcompanyid() + "'");
		//查询职员
		List<Person> persons = personService.selectPerson(psql.toString());
		//把数据传到页面
		request.setAttribute("fnumber", number);
		request.setAttribute("department", department);
		request.setAttribute("persons", persons);
		request.setAttribute("type", type);
		return "/backHome/personData/coaceGroups/editCoaceGroups";
	}
	
	/**
	 * 查询教练队
	 * @return
	 */
	@RequestMapping("/queTeam")
	@ResponseBody
	public List<Team> queTeam(String name, HttpServletRequest request) {
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		List<Team> teams = new ArrayList<>();
		if(name == null){
			teams = teamService.queryTeam(user.getFcompanyid());
		}else{
			teams = teamService.queryTeamByName(name, user.getFcompanyid());
		}
		return teams;
	}
	/**
	 * 根据fid查询
	 * @param fid
	 * @return
	 */
	@RequestMapping("/queTeamByFid")
	@ResponseBody
	public Team queTeamByFid(String fid){
		Team team = teamService.queryTeamByFid(fid);
		return team;
	}
	
	/**
	 * 添加教练组
	 * @param request
	 * @param coaceGroup 属性自动封装
	 * @return
	 */
	@RequestMapping("/addCoaceGroup")
	public String addCoaceGroup(HttpServletRequest request,CoaceGroup coaceGroup){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//利用UUID生成fid
		String fid = GetFid.UUIDIntoFid();
		coaceGroup.setFid(fid);
		//控制单元id
		coaceGroup.setFcontrolunitid(user.getFcompanyid());
		//创建人id
		coaceGroup.setFcreatorid(user.getFid());
		//公司id
		coaceGroup.setCfficompanyid(user.getFcompanyid());
		//获取当前时间
		String createTime = TimeFormat.timeFormat(new Date());
		coaceGroup.setFcreatetime(createTime);
		//把属性添加进去
		coaceGroupService.addCoaceGroup(coaceGroup);
		//获取子类信息
		String[] fseq = request.getParameterValues("fseq");
		//跟父类的cfpersonid字段区分
		String[] cfpersonid = request.getParameterValues("cfpersonid2");
		if(fseq == null || fseq.length == 0){
			
		}else{
			for (int i = 0; i < fseq.length; i++) {
				//添加子类信息
				CoaceGroupEntry coaceGroupEntry = new CoaceGroupEntry();
				coaceGroupEntry.setCfpersonid(cfpersonid[i]);
				coaceGroupEntry.setFid(GetFid.UUIDIntoFid());
				coaceGroupEntry.setFparentid(fid);
				coaceGroupEntry.setFseq((long) i+1);
				coaceGroupEntryService.addCoaceGroupEntry(coaceGroupEntry);
			}
		}
		//添加日志
		customLogService.addLog("职员基础资料", createTime+"对教练队进行添加操作", null, user.getFid());
		//重定向到添加页面
		return "redirect:/DrivingSys/insertCoaceGroup?type=3";
	}
	
	/**
	 * 删除教练队
	 * @param request
	 * @param deleteId 多个
	 * @param fid 单个
	 * @return
	 */
	@RequestMapping("/deleteCoaceGroupByFid")
	public String deleteCoaceGroupByFid(HttpServletRequest request,String deleteId[],String fid){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		if(fid == null || "".equals(fid)){
			for (int i = 0; i < deleteId.length; i++) {
				//删除子类信息
				coaceGroupEntryService.deleteByFparentId(deleteId[i]);
				//删除父类信息
				coaceGroupService.deleteCoaceGroupByFid(deleteId[i]);
			}
		}else{
			//删除子类信息
			coaceGroupEntryService.deleteByFparentId(fid);
			//删除父类信息
			coaceGroupService.deleteCoaceGroupByFid(fid);
		}
		//添加日志
		customLogService.addLog("职员基础资料", TimeFormat.timeFormat(new Date())+"对教练队进行删除操作", null, user.getFid());
		//调用查询的方法
		queryCoaceGroup(request, null);
		return "/backHome/personData/coaceGroups/coaceGroupsList";
	}
	
	/**
	 * 根据fid查询
	 * @param request
	 * @param fid
	 * @return
	 */
	@RequestMapping("/selectCoaceGroupByFid")
	public String selectCoaceGroupByFid(HttpServletRequest request,String fid){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//查询组织
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//拼接SQL语句
		StringBuffer psql = new StringBuffer();
		psql.append("select T.FID, T.FNUMBER,to_char(t.CFBIRTHDAY,'YYYY-MM-DD ') cfbirthdays,to_char(t.cfstartdate,'YYYY-MM-DD ') cfstartdate,");
		psql.append("to_char(t.cfenddate,'YYYY-MM-DD ') cfenddate,to_char(t.cfbegindate,'YYYY-MM-DD ') cfbegindate,to_char(t.CFHTDQSJ,'YYYY-MM-DD ') cfhtdqsj,");
		psql.append("T.CFIDCARDNO, T.CFCELL, T.CFADDRESS,T.CFPERSONTYPE, T.CFSEX,T.CFXCTZ, T.CFGWYD, T.CFQJJL, T.CFWJJLJL,p.fname_l2 as positiongradeName,t.cfaccountsno, ");
		psql.append("T.CFSHJLJL,T.FNAME_L2,T.CFZSTC,T.CFPXTC,A.FNAME_L2 AS CFPERSONDEPNAME,C.fnumber AS CFCARNAME from ct_ds_person t left join ");
		psql.append("CT_DS_ADMIN A ON A.FID=T.CFPERSONDEPID left join CT_DS_CAR C ON C.FID=T.CFCARID left join CT_DS_POSITIONGRADE p on t.cfjobgradeid=p.fid ");
		//查询职员
		List<Person> persons = personService.selectPerson(psql.toString());
		//查询对象
		CoaceGroup coaceGroup = coaceGroupService.queryCoaceGroupByFid(fid);
		//查询子类对象
		List<CoaceGroupEntry> coaceGroupEntrys = coaceGroupEntryService.queryByFparentId(fid);
		//把数据传到页面
		request.setAttribute("department", department);
		request.setAttribute("coaceGroupEntrys", coaceGroupEntrys);
		request.setAttribute("coaceGroup", coaceGroup);
		request.setAttribute("persons", persons);
		return "/backHome/personData/coaceGroups/editCoaceGroups";
	}
	
	/**
	 * 修改教练组
	 * @param request
	 * @param coaceGroup 属性自动封装
	 * @return
	 */
	@RequestMapping("/modifyCoaceGroup")
	public String modifyCoaceGroup(HttpServletRequest request,CoaceGroup coaceGroup){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//控制单元id
		coaceGroup.setFcontrolunitid(user.getFcompanyid());
		//创建人id
		coaceGroup.setFlastupdateuserid((user.getFid()));
		//公司id
		coaceGroup.setCfficompanyid(user.getFcompanyid());
		//获取当前时间
		String updateTime = TimeFormat.timeFormat(new Date());
		coaceGroup.setFlastupdatetime(updateTime);
		//修改
		coaceGroupService.modifyCoaceGroup(coaceGroup);
		//先把子类数据删除
		coaceGroupEntryService.deleteByFparentId(coaceGroup.getFid());
		//获取子类信息
		String[] fseq = request.getParameterValues("fseq");
		//跟父类的cfpersonid字段区分
		String[] cfpersonid = request.getParameterValues("cfpersonid2");
		if(fseq == null || fseq.length == 0){
					
		}else{
			for (int i = 0; i < fseq.length; i++) {
				//添加子类信息
				CoaceGroupEntry coaceGroupEntry = new CoaceGroupEntry();
				coaceGroupEntry.setCfpersonid(cfpersonid[i]);
				coaceGroupEntry.setFid(GetFid.UUIDIntoFid());
				coaceGroupEntry.setFparentid(coaceGroup.getFid());
				coaceGroupEntry.setFseq((long) i+1);
				coaceGroupEntryService.addCoaceGroupEntry(coaceGroupEntry);
			}
		}
		//添加日志
		customLogService.addLog("职员基础资料", updateTime+"对教练队进行修改操作", null, user.getFid());
		//调用查询的方法
		return commonController.skipUrl("/queryCoaceGroup/look.action");
	}
	
	@SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类 
	 * @throws Exception
	 */
	public PageBean<CoaceGroup> getPageBean(HttpServletRequest request,String companyId) throws Exception
	{

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){  
			offset=0;  
		}else{  
			offset=Integer.parseInt(request.getParameter("pager.offset"));  
		}	
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("select t.fid fid,t.fnumber fnumber,t.fname_l2 fnameL2,p.fname_l2 groupName,te.fname_l2 as teamName,t.cfkemu cfkemu,");
		psql.append(" pe.fname_l2 duichangName from ct_ds_coacegroup t  left join ct_ds_person p on t.cfpersonid=p.fid left join ct_ds_team te on t.cfteamid=te.fid");
		psql.append(" left join ct_ds_person pe on t.cfduizhangid=pe.fid ");
		psql.append(" where t.FCONTROLUNITID= '"+companyId+"' order by t.fcreatetime desc");
		int psize=15; //每页显示数
		int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= coaceGroupService.selectPage(pindex, psql.toString(), psize);
		PageBean<CoaceGroup> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<CoaceGroup>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}

    /**
     * @Author lcx
     * @Date 2017/11/22 0022 上午 10:48
     * 查询 科目二分车教练组列表分页
     */
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/getPageCoaceGroup")
    public Map getPageCoaceGroup(HttpServletRequest request, @RequestParam(defaultValue = "", value = "name") String name, @RequestParam(defaultValue = "") String cfsjhm, @RequestParam(defaultValue = "1") String pindex) throws Exception {

		User user = (User) request.getSession().getAttribute("user");

        String psql = "SELECT " +
                "	t.fid," +
                "  T.FNAME_L2, " +
                "  T.FNUMBER, " +
                "  t.FSIMPLENAME, " +
                "  t.FDESCRIPTION_L2, " +
                "  TO_CHAR(t.FCREATETIME, 'YYYY-MM-DD') FCREATETIME, " +
                "  U.NAME createName, " +
                "  TO_CHAR(t.FLASTUPDATETIME, 'YYYY-MM-DD') FLASTUPDATETIME, " +
                "  U1.NAME updateName, " +
                "  a.FNAME_L2 cwzzName, " +
                "  T1.FSEQ, " +
                "  P1.FNAME_L2 jlName, " +
                "  P2.FNAME_L2 zzName, " +
                "  P3.FNAME_L2 dzName, " +
                "  te.FNAME_L2 jldName, " +
                "  te.CFKEMU kmName " +
                " FROM ct_ds_coacegroup t LEFT JOIN ct_ds_coacegroupentry t1 ON t.fid = t1.FPARENTID " +
                "  LEFT JOIN ct_ds_person P ON T1.CFPERSONID = P.FID " +
                "  LEFT JOIN T_E_USER U ON T.FCREATORID = U.FID " +
                "  LEFT JOIN T_E_USER U1 ON T.FLASTUPDATEUSERID = U1.FID " +
                "  LEFT JOIN CT_DS_ADMIN A ON t.FCONTROLUNITID = a.FID " +
                "  LEFT JOIN CT_DS_PERSON P1 ON T1.CFPERSONID = P1.FID " +
                "  LEFT JOIN CT_DS_PERSON P2 ON T.CFPERSONID = P2.FID " +
                "  LEFT JOIN CT_DS_PERSON P3 ON T.CFDUIZHANGID = P3.FID " +
                "  LEFT JOIN CT_DS_TEAM te ON t.CFTEAMID = te.FID " +
				" where P1.FNAME_L2 like '%" + name + "%' and t.FCONTROLUNITID='" + user.getFcompanyid() + "'";

        int psize = 15; //每页显示数
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = coaceGroupService.selectPage(Integer.valueOf(pindex), psql, psize);
        PageBean<Person> pb = new PageBean<>();
        pb.setPc(Integer.valueOf(pindex)); //页码
        Map<String, Object> paramMapCount = getPageBeanCount(psql); //取记录总数
        pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
        pb.setPs(psize);
        Map stu = new HashMap();
        stu.put("sList", (List<Person>) paramMap.get("v_cur"));

        stu.put("pb", (pb.getTr() / pb.getPs()));

        return stu; //每页数据集;

    }

    /**
     * @Author lcx
     * @Date 2017/11/22 0022 下午 3:28
     * ajax查询教练组
     */
    @RequestMapping(value = "/selectCoaceGroupByFidAsPage")
    @ResponseBody
    public Object selCoaceGroupById(@RequestParam(value = "id", required = false) String id) throws Exception {
        List<CoaceGroup> coaceGroupArrayList = new ArrayList<CoaceGroup>();
        String[] ids = id.split(",");
        for (int i = 0; i < ids.length; i++) {
            CoaceGroup sharecartworegentry = coaceGroupService.queryCoaceGroupByFid(ids[i]);
            coaceGroupArrayList.add(sharecartworegentry);
        }
        return coaceGroupArrayList;
    }



	/**
	 * 取记录总数 dmz 20160921
	 * @param psql  SQL语句
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getPageBeanCount(String psql) throws Exception
	{

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap=coaceGroupService.selectPageCount(psql);
		return paramMap;		
	}

    /**
     * 导出Excel
     *
     * @param request
     * @param response
     * @param fnameL2
     */
    @RequestMapping("/importCoaceGroup")
    public void importCoaceGroup(HttpServletRequest request, HttpServletResponse response, String fnameL2) {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        //定义接收类型
        List<Object> data = new ArrayList<>();
        //查询数据
        List<CoaceGroup> coaceGroups = coaceGroupService.selectCoaceGroupByInfo(user.getFcompanyid(), fnameL2.trim());
        for (CoaceGroup coaceGroup : coaceGroups) {
            data.add(coaceGroup.getFnumber());
            data.add(coaceGroup.getFnameL2());
            data.add(coaceGroup.getGroupName());
            data.add(coaceGroup.getDuichangName());
            data.add(coaceGroup.getTeamName());
            data.add(stateToString.subject(coaceGroup.getCfkemu()));
        }
        //头部数据
        String head[] = {"编码", "名称", "组长", "队长", "教练队", "科目"};
        //长度
        Integer length[] = {6500, 3000, 3000, 3000, 3000, 2600};
        try {
            //导出Excel
            CommonExport.importExcel(response, "教练组" + TimeFormat.getNowTime2() + ".xls", "教练组", data, head, length);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
